package de.gameduell.framework.locale {
	import de.gameduell.framework.debug.Debug;	

	/**
	 * @author cbra
	 */
	public class LocaleTools {
		
		public static const VARIABLE:RegExp =  /(§{1}.+§{1})|§{1}[^§]+/; 
		/**
		 * this function convert a string into a logical expression
		 * and return its value
		 */
		public static function compareCondition(nodeValue:String, comparison:String, localValue:String):Boolean {
			switch(comparison) {
				case "<":  return (Number(localValue) < Number(nodeValue));
				case ">":  return (Number(localValue) > Number(nodeValue));
				case "<=": return (Number(localValue) <= Number(nodeValue));
				case "=":  return (localValue == nodeValue);
				case ">=": return (Number(localValue) >= Number(nodeValue));
				default :
					throw new Error("illegal comparison used in locale.xml " + comparison);			
			}
			return false;
		}
		
		/**
		 * splits a string which represents a logical expression into its
		 * elements and returns them in an array
		 */
		public static function splitCondition(condition:String):Array{
			const elementsReg:RegExp = /\w{1,}|[\<=\>]{1,2}/g;
			const whiteSpaceReg:RegExp = /\s{1,}/g;
			condition.replace(whiteSpaceReg, "");
			return condition.match(elementsReg); 	
		}
		
		/**
		 * converts squared brackets into angle brackets
		 */
		public static function convertBrackets(text:String):String{
			const left:RegExp  = /\[/g;  
			const right:RegExp = /\]/g;  
			text = text.replace(left, "<");  
			text = text.replace(right, ">");  
			return text;
		}
		
		public static function containsVar(aWord:String):Boolean{
			return VARIABLE.test(aWord);		
		}
		
		public static function replaceVar(aWord:String,newValue:String):String{
			return aWord.replace(VARIABLE,newValue);
		}
		
		public static function replaceVariables(original:String,localeData:LocaleData):String{
			var replacedString:String = "";
			try {
				if(original.length>0){
					var words:Array = original.split(DynamicContent.DELIMITER);				
					for(var i:* in words) {
						if(LocaleTools.containsVar(words[i])) {
							var key:String = LocaleTools.extractVarName(words[i]);
							words[i] = LocaleTools.replaceVar(words[i],localeData.getValue(key));
						}
					}
					replacedString = words.join(DynamicContent.DELIMITER);
				}
			}catch(e:Error) {
				Debug.trace("DynamicContent::replaceVariables original: " + original + " " + e, Debug.ERROR);
			}
			return replacedString;
		}

		public static function extractVarName(aString:String):String {
			const pre:RegExp = /[^§]*§{1}/;
			const post:RegExp = /§{1}.*/;
			aString = aString.replace(pre, "");
			aString = aString.replace(post, "");
			return aString;
		}

		public static function isURL(aString:String):Boolean {
			if(aString != null) {
				return(aString.indexOf("http://") == 0 || aString.indexOf("https://") == 0);
			}
			return false;
		}
	}
}
